package com.yanyeori.framework.redis.listener;

import com.yanyeori.framework.core.util.SpringUtil;
import com.yanyeori.framework.redis.model.PushMessage;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * redis监听消息处理器
 *
 * @author chenkuan 2022/5/9
 */
@Slf4j
public class RedisListenerHandler {

    private static volatile RedisListenerHandler instance;
    private Map<String, List<RedisListener>> handlers;

    private RedisListenerHandler() {
        init();
    }

    public static RedisListenerHandler getInstance() {
        if (instance == null) {
            synchronized (RedisListenerHandler.class) {
                if (instance == null) {
                    instance = new RedisListenerHandler();
                }
            }
        }
        return instance;
    }

    public void handle(PushMessage message) {
        if (!handlers.containsKey(message.getTopic())) {
            log.warn("No handler is found for the subscription topic: {}", message.getTopic());
            return;
        }
        handlers.get(message.getTopic()).forEach(handler -> handler.receive(message.getData()));
    }

    private void init() {
        handlers = new HashMap<>();
        Collection<RedisListener> listeners = SpringUtil.getBeansOfType(RedisListener.class).values();
        for (RedisListener listener : listeners) {
            handlers.computeIfAbsent(listener.topic, k -> new ArrayList<>()).add(listener);
        }
    }
}
